package com.zjs.redis.redisson;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Configuration
public class RedissonConfig {

    @Autowired
    private RedisConfigProperties redisConfig;

    @Data
    @Component
    @ConfigurationProperties(prefix = "spring.redis")
    class RedisConfigProperties {
        private String password;
        private RedisClusterConfigProperties cluster = new RedisClusterConfigProperties();

        @Data
        class RedisClusterConfigProperties {
            private String[] nodes;
        }
    }


    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        String[] nodes = redisConfig.getCluster().getNodes();
        ClusterServersConfig clusterServersConfig = config.useClusterServers();
        for (String nodeUrl : nodes) {
            clusterServersConfig.addNodeAddress("redis://" + nodeUrl);
        }
        clusterServersConfig.setPassword(redisConfig.getPassword());
        return Redisson.create(config);
    }
}
